package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BussinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {
    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipFaceTemplate aipFaceTemplate;


    /**
     * 保存用户数据
     *
     * @param userInfo
     */
    public void save(UserInfo userInfo) {
        //直接发起远程调用完成数据的保存
        userInfoApi.save(userInfo);

    }

    /**
     * 更新用户图像
     *
     * @param headPhoto
     * @param id
     * @throws IOException
     */
    public void updae(MultipartFile headPhoto, Long id) throws IOException {
        //1、先把图片上传到阿里云oss上，获取图片的地址url
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云进行图片的校验，如果校验不通过直接抛出异常，如果校验通过了执行下一步操作
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //如果没有人脸,抛出异常
        if (!detect) {
            throw new BussinessException(ErrorResult.faceError());
        } else {
            //3、如果有人脸 就更新tb_user_info表【进行远程调用】
            UserInfo userInfo = new UserInfo();
            userInfo.setId(Long.valueOf(id));
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);

        }

    }

    /**
     * 根据Id查询
     *
     * @param id
     * @return
     */
//     public UserInfo findById(Long id) {
//        return userInfoApi.findById(id);
//    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo,vo); //copy同名同类型的属性

        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }


    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}

